透過 userEvent
可以更好的去模擬 user 的行為
常用的會有
我們今天會用到的只有 click ,其他如果有需要都可以去看官方文檔
先建立一個 checkbox 的 component,寫得有點隨便
import { useState } from "react";
const Checkbox = () => {
const selections = [
{ label: "Apple", isChecked: false },
{ label: "Banana", isChecked: false },
{ label: "Cherry", isChecked: false },
]
const [selectedItems, setSelectedItems] = useState(selections);
return (
<div>
{selectedItems.map((item, index) => (
<div key={item.label}>
<input
type="checkbox"
id={item.label}
name={item.label}
checked={item.isChecked}
onChange={(event) => {
const newItems = [...selectedItems];
newItems[index].isChecked = event.target.checked;
setSelectedItems(newItems);
}}
/>
<label htmlFor={item.label}>{item.label}</label>
</div>
)
)}
</div>
);
};
export default Checkbox;
那這次要測試的有
import userEvent from '@testing-library/user-event';
import Checkbox from '.';
import { render , screen, waitFor} from '@testing-library/react';
import '@testing-library/jest-dom';
describe('Checkbox', () => {
it('should render the checkbox with the label', async () => {
render(<Checkbox />);
const checkbox = await screen.findByRole('checkbox', { name: 'Apple' });
expect(checkbox).toBeInTheDocument();
});
it('should be checked when clicking', () => {
render(<Checkbox />);
const checkbox = screen.getByRole('checkbox', { name: 'Apple' });
userEvent.click(checkbox);
waitFor(() => {
expect(checkbox).toBeChecked();
});
});
it('should be unchecked when clicking twice', () => {
render(<Checkbox />);
const checkbox = screen.getByRole('checkbox', { name: 'Apple' });
userEvent.click(checkbox);
userEvent.click(checkbox);
waitFor(() => {
expect(checkbox).not.toBeChecked();
});
});
});
需要注意的是 '@testing-library/jest-dom'
要記得 import 進來,不然有時候測試會 fail 。userEvent
的用法其實很簡單,先找到你要操作的 element ,在使用 userEvent 去模擬需要的操作,最後再確認畫面是否跟預期相同。
希望大家的專案都可以讓 bug 想遁形卻無所遁形